package com.ds.infrastructure.hyperspace.console.common.methodlock;

import com.ds.infrastructure.hyperspace.console.entity.table.TbMethodLock;
import com.ds.infrastructure.hyperspace.console.service.inf.IMethodLockService;
import com.ds.infrastructure.hyperspace.console.utils.AspectUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class MethodLockAspect {

    @Autowired
    IMethodLockService iMethodLockService;

    @Around(value = "@annotation(MethodLock)")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) {
        Method method = AspectUtil.getMethod(proceedingJoinPoint);
        MethodLock methodLock = AspectUtil.getAnnotation(method, MethodLock.class);
        Object[] args = proceedingJoinPoint.getArgs();
        if (args.length < 1) {
            throw new MethodLockException("MethodLock异常：没找到MethodLockId参数");
        }
        Object firstObj = args[0];
        if (!(firstObj instanceof MethodLockId)) {
            throw new MethodLockException("MethodLock异常：没找到MethodLockId参数");
        }
        TbMethodLock record = new TbMethodLock();
        record.setMethodName(methodLock.name());
        record.setMethodId(((MethodLockId) firstObj).getId());
        try {
            iMethodLockService.save(record);
            return proceedingJoinPoint.proceed();
        } catch (DuplicateKeyException ex) {
            throw new MethodLockException("MethodLock异常：当前方法以被锁定",true);
        } catch (Throwable throwable) {
            throw new IllegalStateException(throwable);
        } finally {
            iMethodLockService.delete(record.getId());
        }

    }
}
